const app = getApp();
var utils = {
  digit: function (n) {
    if (n == null || n === "" || n == undefined) {
      return "";
    } else {
      n = n.toString();
      return n[1] ? n : '0' + n;
    }
  },
  formatDate: function (date = new Date()) {
    // 年月日
    var year = date.getFullYear()
    var month = date.getMonth() + 1
    var day = date.getDate()
    // 返回值
    return [year, this.digit(month)].map(this.digit).join('-');
  }
}

Page({
  data: {
    g_iphone: '',
    click: 'on',
    click_stop: 'off',
    // 左右滑动的class样式
    slideOne: "",
    slideTwo: "",
    // 左右滑动定义的状态变量
    slideFlag: false,

    // 页面输出的数据
    currentDate: utils.formatDate(),
    weeks: ['日', '一', '二', '三', '四', '五', '六'],
    renwu_url: '//resource.160nurse.com/canvas/healthy/img/bmi/female_bz.png',
    curDate: '',
    next: false
  },
  onLoad: function () {
    var that = this;
    console.log('缓存数据', wx.getStorageSync('isGetChicken'))
    this.setData({
      userInfo: {
        nick_name: wx.getStorageSync('nickname'),
        img_src: wx.getStorageSync('icon'),
        addr: wx.getStorageSync('zone_name')
      },
      isGet: wx.getStorageSync('isGetChicken')
    })
    this.generateDaily()
    // this.getDailyData()
    this.getData()
    this.getStatus()
    console.log(that.data.userInfo.isGet)
		//公告
		app.request(app.apiDomain + "index.php?c=mall&a=notice", {
			type:'checkin'
		}, function (res) {
			// console.log(res.data.data)
			that.setData({
				gao:res.data.data
			});
		});
  },
  // 获取早起守约活动状态
  getStatus () {
     let that= this
    app.request(app.apiDomain + 'index.php?c=activity&a=queryStatus', {}, function (res) {
      let status_text = ''
      let status_font = ''
      if (res.data.status == 1) {
        if (res.data.data && !!res.data.data.hasOwnProperty('status')) {
          if (res.data.data.status == 0) {
            status_text = res.data.data.shor_name.substring(1,3)
            status_font = '活动报名中'
          } else if (res.data.data.status == 1) {
            status_text = res.data.data.shor_name.substring(1, 3)
            status_font = '活动进行中'
          } else{
            status_text = res.data.data.shor_name.substring(1, 3)
            status_font = '活动已结束'
          }
        } else{
          status_text = ''
        }
      } else{
        status_text = ''
        status_font = ''
      }
      that.setData({
        status_text: status_text,
        status_font: status_font
      })
    })
  },
  getData () {
    let that = this
    app.request(app.apiDomain + 'index.php?c=point&a=newchecklist', {
      month: that.data.currentDate
    }, function (res) {
      if (res.data.status == '1') {
        console.log(typeof res.data.data.today);
        var click = '';
        var stop = '';
        var point = 0;
        if (!!res.data.data.today) {
          click = 'on';
          stop = 'off';
          point = res.data.data.today.checkin_point;
          var date = new Date();
          var today = date.getFullYear() + '-' + date.getMonth() + '-' + date.getDate();
          wx.setStorageSync("checkin_point", today + ':' + res.data.data.today.checkin_point);

        }
        if (!wx.getStorageSync('isGetChicken') && res.data.data.total >= 30 && res.data.data.total < 60) {
          wx.setStorageSync('isGetChicken', '1')
          let list = res.data.data.list
          for (var key in list) {
            let date = list[key].checkin_date.split('-')[2]
            list[key]['date'] = parseInt(date)
          }
          that.setData({
            checklist: list,
            click: 'on',
            click_stop: 'off',
            // point: res.data.data.today.checkin_point,
            total: res.data.data.total,
            isGet: wx.getStorageSync('isGetChicken'),
            isClick: true
          });
          console.log('签到true', that.data.isClick, that.data.isGet)
        } else if (!wx.getStorageSync('isGetChicken') && res.data.data.total >= 60 && res.data.data.total < 90) {
          wx.setStorageSync('isGetChicken', '2')
          let list = res.data.data.list
          for (var key in list) {
            let date = list[key].checkin_date.split('-')[2]
            list[key]['date'] = parseInt(date)
          }
          that.setData({
            checklist: list,
            click: 'on',
            click_stop: 'off',
            // point: res.data.data.today.checkin_point,
            total: res.data.data.total,
            isGet: wx.getStorageSync('isGetChicken'),
            isClick: true
          });
          console.log('签到true', that.data.isClick, that.data.isGet)
        } else if (!wx.getStorageSync('isGetChicken') && res.data.data.total >= 90 ) {
          wx.setStorageSync('isGetChicken', '3')
          let list = res.data.data.list
          for (var key in list) {
            let date = list[key].checkin_date.split('-')[2]
            list[key]['date'] = parseInt(date)
          }
          that.setData({
            checklist: list,
            click: 'on',
            click_stop: 'off',
            // point: res.data.data.today.checkin_point,
            total: res.data.data.total,
            isGet: wx.getStorageSync('isGetChicken'),
            isClick: true
          });
          console.log('签到true', that.data.isClick, that.data.isGet)
        } else if (!!wx.getStorageSync('isGetChicken')) {
          let list = res.data.data.list
          for (var key in list) {
            let date = list[key].checkin_date.split('-')[2]
            list[key]['date'] = parseInt(date)
          }
          let isGet = res.data.data.total >= 30 && res.data.data.total < 60 ? '1' : res.data.data.total >= 60 && res.data.data.total < 90 ? '2' : res.data.data.total >= 90 ? '3' : ''
          wx.setStorageSync('isGetChicken', isGet)
          that.setData({
            checklist: list,
            click: 'on',
            click_stop: 'off',
            // point: res.data.data.today.checkin_point,
            total: res.data.data.total,
            isGet: isGet,
            isClick: false
          });
          console.log('签到false', that.data.isClick, that.data.isGet)
        }

        let list = res.data.data.list
        for (var key in list ) {
          let date = list[key].checkin_date.split('-')[2]
          list[key]['date'] = parseInt(date)
        }
        var lx_time = 0
        if (!res.data.data.num) {
          lx_time = 0
        } else {
          lx_time = res.data.data.num
        }
        that.setData({
          checklist: list,
          click: click,
          click_stop: stop,
          point: point,
          timeList: res.data.data.days,
          lian_xu_time: lx_time,
          total: res.data.data.total ? res.data.data.total : 0
        });
      }
    })
  },
	gao_click:function(){
		this.setData({
			gao_on:'on'
		})
	},
	gao_off:function(){
		this.setData({
			gao_on:''
		})
	},
  close_medal: function () {
    console.log(222)
    this.setData({
      isClick: false
    })
  },
	top_click:function(){
    var that = this;
    app.request(app.apiDomain + 'index.php?c=point&a=checkin', {}, function (res) {
      if (res.data.status == '1') {
        app.sleepPoint = res.data.data.today.checkin_point;
        console.log(app.sleepPoint);
        if (!wx.getStorageSync('isGetChicken') && res.data.data.today.total_num >= 30 & res.data.data.today.total_num < 60) {
          let isGet = res.data.data.today.total_num >= 30 && res.data.data.today.total_num < 60 ? '1' : res.data.data.today.total_num >= 60 && res.data.data.today.total_num < 90 ? '2' : res.data.data.today.total_num >= 90 ? '3' : '0'
          wx.setStorageSync('isGetChicken', isGet)
          let list = res.data.data.list
          for (var key in list) {
            let date = list[key].checkin_date.split('-')[2]
            list[key]['date'] = parseInt(date)
          }
          that.setData({
            checklist: list,
            click: 'on',
            click_stop: 'off',
            point: res.data.data.today.checkin_point,
            total: res.data.data.today.total_num,
            isGet: wx.getStorageSync('isGetChicken'),
            isClick: true
          });
          console.log('签到true', that.data.isClick, that.data.isGet)
        } else if (!!wx.getStorageSync('isGetChicken')) {
          let list = res.data.data.list
          for (var key in list) {
            console.log(key, list[key].checkin_date)
            let date = list[key].checkin_date.split('-')[2]
            list[key]['date'] = parseInt(date)
          }
          let isGet = res.data.data.today.total_num >= 30 && res.data.data.today.total_num < 60 ? '1' : res.data.data.today.total_num >= 60 && res.data.data.today.total_num < 90 ? '2' : res.data.data.today.total_num >= 90 ? '3' : '0'
          wx.setStorageSync('isGetChicken', isGet)
          that.setData({
            checklist: list,
            click: 'on',
            click_stop: 'off',
            point: res.data.data.today.checkin_point,
            total: res.data.data.today.total_num,
            isGet: isGet,
            isClick: false
          });
          console.log('签到false', that.data.isClick, that.data.isGet)
        }
        console.log(that.data.checklist)
        var date = new Date();
        var today = date.getFullYear() + '-' + date.getMonth() + '-' +  date.getDate();
        wx.setStorageSync("checkin_point", today + ':' + res.data.data.today.checkin_point);
        app.request(app.apiDomain + 'index.php?c=point&a=newchecklist', {}, function (res) {
          if (res.data.status == '1') {
            console.log(res.data.data);
            var click = '';
            var stop = '';
            var point = 0;
            if (!!res.data.data.today) {
              click = 'on';
              stop = 'off';
              point = res.data.data.today.checkin_point;
              var date = new Date();
              var today = date.getFullYear() + '-' + date.getMonth() + '-' + date.getDate();
              wx.setStorageSync("checkin_point", today + ':' + res.data.data.today.checkin_point);

            }
            var lx_time = 0
            if (!res.data.data.num) {
              lx_time = 0
            } else {
              lx_time = res.data.data.num
            }
            let list = res.data.data.list
            for (var key in list) {
              let date = list[key].checkin_date.split('-')[2]
              list[key]['date'] = parseInt(date)
            }
            console.log('stop', stop)
            that.setData({
              checklist: list,
              click: click,
              click_stop: stop,
              point: point,
              timeList: res.data.data.days,
              lian_xu_time: lx_time,
              total: res.data.data.total
            });
          }
        });
      }else {
        wx.showToast({
          title: res.data.info,
          icon:"none"
        });
      }
    });	
	},
	gao_click:function(){
		this.setData({
			gao_on:'on'
		})
	},
	gao_off:function(){
		this.setData({
			gao_on:''
		})
	},
  generateDaily() {
    let date = new Date(this.data.currentDate)
    let year = date.getFullYear()
    let month = date.getMonth()
    let day = date.getDate()
    let isRunnian = this.calculatYear(year)
    // let current_date = new Date()
    // let current_year = current_date.getFullYear()
    // let current_month = current_date.getMonth()
    // if (current_year == year && month == current_month) {
    //   this.setData({
    //     next: false
    //   })
    // } else {
    //   this.setData({
    //     next: true
    //   })
    // }
    let days = []
    if (isRunnian) {
      days = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    } else {
      days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    }
    // 计算月第一天是星期几,以及上个月的天数
    let fistDay = new Date(year + '/' + (month + 1) + '/01').getDay()
    let preDays = 0
    if (month == 0) {
      preDays = days[11]
    } else {
      preDays = days[month - 1]
    }
    //计算最后一天是星期几
    let lastDay = new Date(year + '/' + (month + 1) + '/' + days[month]).getDay()
    let lastDays = 0
    if (month == 11) {
      lastDays = days[0]
    } else {
      lastDays = days[month + 1]
    }
    console.log(lastDay, lastDays, fistDay, preDays)
    this.setData({
      days,
      month,
      preDays,
      fistDay,
      lastDay,
      lastDays
    })
  },
  // 计算闰年还是平年
  calculatYear(year) {
    if (year % 4 == 0 && year % 100 != 0) {
      return true
    } else {
      return false
    }
  },
  touchStart(e) {
    this.setData({
      startX: e.changedTouches[0].pageX
    })
  },
  touchEnd(e) {
    if (!this.data.slideFlag) {
      this.setData({
        slideFlag: true,
        endX: e.changedTouches[0].pageX
      })
      let disX = e.changedTouches[0].pageX - this.data.startX;
      if (disX < -150) {
        console.log("左滑", this.data.next)
          this.setData({
            slideOne: "animated fadeOutLeft",
            slideTwo: "animated fadeInRight"
          })
          setTimeout(() => {
            this.tapNext();
          }, 300);
          setTimeout(() => {
            this.setData({
              slideFlag: false,
              slideOne: "",
              slideTwo: ""
            })
          }, 800);        
      } else if (disX > 150) {
        console.log("右滑")
        this.setData({
          slideOne: "animated fadeOutRight",
          slideTwo: "animated fadeInLeft"
        })
        setTimeout(() => {
          this.tapPrev();
        }, 300);
        setTimeout(() => {
          this.setData({
            slideFlag: false,
            slideOne: "",
            slideTwo: ""
          })
        }, 800);
      } else {
        this.setData({
          slideFlag: false
        })
      }
    }
  },
  /**
   * 左右点击
   */
  clickSlide(e) {
    if (!this.data.slideFlag) {
      this.setData({
        slideFlag: true,
        endX: e.changedTouches[0].pageX
      })
      let disX = e.changedTouches[0].pageX - this.data.startX;
      if (e.target.dataset.str == 'next') {
        console.log(this.data.next)
        // if (!this.data.next) {
        //   return false
        // }
        this.setData({
          slideOne: "animated fadeOutLeft",
          slideTwo: "animated fadeInRight"
        })
        setTimeout(() => {
          this.tapNext();
        }, 300);
        setTimeout(() => {
          this.setData({
            slideFlag: false,
            slideOne: "",
            slideTwo: ""
          })
        }, 800);
      } else if (e.target.dataset.str == 'prev') {
        console.log("右滑")
        this.setData({
          slideOne: "animated fadeOutRight",
          slideTwo: "animated fadeInLeft"
        })
        setTimeout(() => {
          this.tapPrev();
        }, 300);
        setTimeout(() => {
          this.setData({
            slideFlag: false,
            slideOne: "",
            slideTwo: ""
          })
        }, 800);
      } else {
        this.setData({
          slideFlag: false
        })
      }
    }
  },
  /**
   * 左右滑动调用的函数
   */
  tapPrev() {
    let date = new Date(this.data.currentDate);
    date.setMonth(date.getMonth() - 1);
    this.setData({
      currentDate: utils.formatDate(date)
    })
    this.generateDaily()
    this.getData()
  },
  tapNext() {
    let date = new Date(this.data.currentDate);
    date.setMonth(date.getMonth() + 1);
    this.setData({
      currentDate: utils.formatDate(date)
    })
    this.generateDaily()
    this.getData()
  },
	onReady:function () {
		var has=this;
		app.SystemInfo(this)
	},	
  onShareAppMessage: function () {
    return app.onShareAppMessage();
  }  
})



